package com.lizhi.yun.core.handler;

import com.lizhi.common.yun.entity.ListResponseResult;
import com.lizhi.utils.StringUtils;
import com.lizhi.utils.json.SamJsonUtil;
import com.lizhi.yun.db.sfrobot.entity.Appointment;
import com.lizhi.yun.db.sfrobot.repository.AppointmentRepo;
import com.lizhi.yun.deploy.NewBaseHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author: lizhi
 * @Description:
 * @Date: create in 2020/11/12 11:24
 */
@Slf4j
@Service
public class AppointmentHandler extends NewBaseHandler {

    @Resource
    private AppointmentRepo appointmentRepo;

    public ListResponseResult doMain(String json){
        Map<String, Object> map = SamJsonUtil.toMap(json);
        PageRequest pageRequest = getPageRequestDesc(map, "createTime");
        Specification<Appointment> specification = new Specification<Appointment>() {
            @Override
            public Predicate toPredicate(Root<Appointment> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
                List<Predicate> list = new ArrayList<Predicate>();
                if (!StringUtils.isEmpty(map.get("hospitalId"))) {
                    list.add(builder.equal(root.get("hospitalId"), map.get("hospitalId")));
                }
                if (!StringUtils.isEmpty(map.get("hospitalIds"))) {
                    CriteriaBuilder.In<String> in = builder.in(root.get("hospitalId"));
                    List<String> hospitalIds = (List<String>) map.get("hospitalIds");
                    for (String string : hospitalIds){
                        in.value(string);
                    }
                    list.add(in);
                }
                if (!StringUtils.isEmpty(map.get("patientName"))) {
                    list.add(builder.like(root.get("patientName"), String.format("%%%s%%", map.get("patientName"))));
                }
                return query.where(list.toArray(new Predicate[list.size()])).getRestriction();
            }
        };
        Page<Appointment> list = appointmentRepo.findAll(specification, pageRequest);
        return getListResult((int) list.getTotalElements(), list.getContent(), map);
    }
}
